package api

import (
	"ginProject/config/global"
	"ginProject/internal/common"
	"ginProject/internal/model"
	"ginProject/internal/request"
	"ginProject/internal/utils/jwt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strings"
)

func Register(c *gin.Context) {
	var registerRequest request.RegisterRequest
	if err := c.ShouldBindJSON(&registerRequest); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 先判断用户是否已经注册
	user := model.CheckUser(registerRequest.Mobile)
	if user.ID > 0 {
		c.JSON(http.StatusOK, gin.H{"msg": "this user is already registered"})
		return
	}
	// 密码加密
	registerRequest.Password = common.EncryptByAes(registerRequest.Password)
	result := model.Register(registerRequest)
	if result != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "user register failed！"})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "user register successfully"})
	}
}

func Login(c *gin.Context) {
	var loginRequest request.LoginRequest
	if err := c.ShouldBindJSON(&loginRequest); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	//登陆时，判断用户是否已经存在
	data := model.CheckUser(loginRequest.Mobile)
	//如果用户存在  进行登陆操作
	if data.ID > 0 {
		// 解密并判断
		decryPassword := common.DecryptByAes(data.Password, loginRequest.Password)
		if decryPassword == false {
			c.JSON(http.StatusBadRequest, gin.H{"msg": "password error"})
			return
		}
		token, err := common.CreateToken(data)
		if err != nil {
			zap.Error(err)
			c.JSON(http.StatusOK, gin.H{
				"msg":  "token created Err:::" + err.Error(),
				"code": http.StatusBadRequest,
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"token": token,
				"msg":   "token created successfully",
				"code":  http.StatusOK,
			})
		}
	} else { //如果用户不存在，则返回信息
		c.JSON(http.StatusOK, gin.H{
			"msg":  "this user is not registered",
			"code": http.StatusBadRequest,
		})
	}
}

func GetUserInfoById(c *gin.Context) {
	token := c.GetHeader("Authorization")
	zap.S().Infow("解析token", zap.String("token", token))
	tokenString := strings.Split(token, " ")
	if len(tokenString) != 2 || tokenString[0] != "Bearer" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or missing Bearer token"})
		c.Abort()
		return
	}
	tokenData := tokenString[1]
	zap.S().Infow("解析成功", zap.String("token value:::", tokenData))

	jwtToken := untils.NewJWT(global.Config.Jwt.Secret)
	result, err := jwtToken.ParseToken(tokenData)
	if err != nil {
		zap.Error(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"data": result,
		"msg":  "success",
		"code": http.StatusOK,
	})
}
